package com.thirtydays.frame.ui.image

import android.Manifest
import android.app.Activity
import android.content.Context
import android.graphics.Bitmap
import android.net.Uri
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.RelativeLayout
import androidx.activity.result.ActivityResultLauncher
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.GridLayoutManager
import com.blankj.utilcode.util.PermissionUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.config.SelectMimeType.TYPE_IMAGE
import com.luck.picture.lib.config.SelectMimeType.TYPE_VIDEO
import com.luck.picture.lib.entity.LocalMedia
import com.thirtydays.frame.R
import com.thirtydays.frame.base.bean.UpdataFile
import com.thirtydays.frame.databinding.ViewSelectImageBinding
import com.thirtydays.frame.util.CoilEngine
import com.thirtydays.frame.util.PictureSelectorUtils
import com.thirtydays.frame.util.XpopHelp
import com.thirtydays.frame.util.ext.saveBitMap
import java.lang.ref.WeakReference

/**
 * @author 小垚
 * @创建时间： 2021/4/21
 * @描述：图片选取页面
 **/
class SelectImageView : RelativeLayout {
    private lateinit var weakActivity: WeakReference<Activity>
    var maxSelectNum = 9
    var openType = SelectMimeType.ofImage()
    val imageAdapter by lazy { ImageAdapter() }
    var images = mutableListOf<LocalMedia>()
    var minkb = 2 * 1024L
    lateinit var mListenter: onClickImageListenter
    lateinit var mDetleListener: onClickImageListenter
    private lateinit var viewBinding: ViewSelectImageBinding

    private val PERMISSIONS_STORAGE = arrayOf<String>(
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.WRITE_EXTERNAL_STORAGE,
        Manifest.permission.CAMERA
    )

    constructor(context: Context?) : this(context, null)
    constructor(context: Context?, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        initView(context)
    }

    private fun initView(context: Context?) {
        viewBinding = ViewSelectImageBinding.inflate(LayoutInflater.from(context), this, true)
        viewBinding.rvImg.layoutManager = GridLayoutManager(context, 3)
        images.add(LocalMedia())
        imageAdapter.setNewInstance(images)
        viewBinding.rvImg.adapter = imageAdapter

        initListener()
    }

    var mPat: ActivityResultLauncher<*>? = null
    fun initActivity(activity: AppCompatActivity, pat: ActivityResultLauncher<Void?>) {
        weakActivity = WeakReference(activity)
        mPat = pat
    }

    fun setOnClickImageListenter(listenter: onClickImageListenter) {
        mListenter = listenter;
    }

    fun setOnDeleteImageListener(listenter: onClickImageListenter) {
        mDetleListener = listenter
    }

    private fun initListener() {
        imageAdapter.setOnItemClickListener { adapter, view, position ->
            if (!PermissionUtils.isGranted(PERMISSIONS_STORAGE.toString())) {
                PermissionUtils.permission(PERMISSIONS_STORAGE.toString())
                    .callback(object : PermissionUtils.FullCallback {
                        override fun onGranted(granted: List<String>) {
                            openFile(adapter, position)
                        }

                        override fun onDenied(deniedForever: List<String>, denied: List<String>) {}
                    })
                    .request()
            } else {
                openFile(adapter, position)
            }
        }

        imageAdapter.addChildClickViewIds(R.id.iv_delete)
        imageAdapter.setOnItemChildClickListener { adapter, view, position ->
            when (view.id) {
                R.id.iv_delete -> {
                    adapter.removeAt(position)
                    if (imageAdapter.data.size < maxSelectNum) {
                        if (imageAdapter.data.size <= 0) {
                            imageAdapter.data.add(LocalMedia())
                        } else {
                            if (imageAdapter.data[imageAdapter.data.size - 1].path != null) {
                                imageAdapter.data.add(LocalMedia())
                            }
                        }
                    }

                    if (this@SelectImageView::mDetleListener.isInitialized) {
                        mDetleListener.onImage(getSelList())
                    }
                }
            }
        }

    }

    private fun openFile(adapter: BaseQuickAdapter<*, *>, position: Int) {
        val item = adapter.getItem(position) as LocalMedia
        val data: MutableList<LocalMedia> = imageAdapter.data
        var list: MutableList<LocalMedia> = ArrayList()
        if (data.size <= maxSelectNum && data[data.size - 1].path == null) {
            list.addAll(data.subList(0, data.size - 1))
        } else {
            list = data
        }
        if (item.path == null) {
            showPhoto(list)
        } else {
            when (PictureMimeType.getMimeType(item.mimeType)) {
                TYPE_IMAGE -> {
                    weakActivity.get().let {

                    }
                }
                TYPE_VIDEO -> {
                    weakActivity.get().let {

                    }
                }
            }
        }
    }

    private fun showPhoto(media: List<LocalMedia>) {
        XpopHelp.showPhoto(weakActivity.get()!!) {
            when (it) {
                0 -> {
                    mPat?.launch(null)
                }
                1 -> {
                    weakActivity.get()?.let { activity ->
                        PictureSelectorUtils.openPhotoAlbum(
                            activity,
                            openType,
                            selList = media.toMutableList(),
                            maxSelectNum
                        ) { files, media ->
                            var medias = mutableListOf<LocalMedia>()
                            medias.addAll(media)
                            if (media.size < maxSelectNum) {
                                medias.add(LocalMedia())
                            }
                            if (this@SelectImageView::mListenter.isInitialized) {
                                files?.let {
                                    mListenter.onImage(it);
                                }
                            }
                            imageAdapter.setNewInstance(medias)

                        }
                    }
                }
            }
        }
    }

    /**
     * 拍照回调
     */
    fun addBitmap(bitmap: Bitmap) {
        var absolutePath = bitmap.saveBitMap()
        var media = LocalMedia().apply {
            path = absolutePath
        }
        var size = imageAdapter.data.size
        imageAdapter.addData(0, media)
        if (size + 1 >= maxSelectNum) {
            imageAdapter.removeAt(imageAdapter.data.size - 1)
        }
    }

    fun getSelList(): List<UpdataFile> {
        var list = when (imageAdapter.data.size) {
            maxSelectNum -> {
                if (imageAdapter.data[imageAdapter.data.size - 1].path == null) {
                    imageAdapter.data.take(maxSelectNum - 1)
                } else {
                    imageAdapter.data
                }
            }
            1 -> {
                if (imageAdapter.data.first().path == null) {
                    mutableListOf()
                } else {
                    imageAdapter.data
                }
            }
            else -> {
                if (imageAdapter.data[imageAdapter.data.size - 1].path == null) {
                    imageAdapter.data.take(imageAdapter.data.size - 1)
                } else {
                    imageAdapter.data
                }
            }
        }
        return PictureSelectorUtils.setList(list)
    }
}

interface onClickImageListenter {
    fun onImage(list: List<UpdataFile>);
}

/**
 * 图片Adapter
 */
class ImageAdapter(data: MutableList<LocalMedia>? = null) :
    BaseQuickAdapter<LocalMedia, BaseViewHolder>(R.layout.recycle_item_image_add, data) {
    override fun convert(holder: BaseViewHolder, media: LocalMedia) {
        if (media.path == null) {
            holder.setGone(R.id.iv_delete, true)
                .setGone(R.id.riv_image, true)
            //                .setVisible(R.id.ll_add, true)
        } else {
            val path = if (media.isCut && !media.isCompressed) {
                // 裁剪过
                media.cutPath
            } else if (media.isCompressed || media.isCut && media.isCompressed) {
                // 压缩过,或者裁剪同时压缩过,以最终压缩过图片为准
                media.compressPath
            } else {
                // 原图
                media.path
            }
            holder.setVisible(R.id.iv_delete, true)
                .setVisible(R.id.riv_image, true)
            //                .setGone(R.id.ll_add, true);
            CoilEngine.INSTANCE
                .loadImage(
                    context,
                    if (PictureMimeType.isContent(path) && !media.isCut && !media.isCompressed) Uri.parse(path)
                        .toString() else path,
                    holder.getView(R.id.riv_image)
                )
        }
    }
}